define(function (require, exports, module) {
    var angular = require('angular');
    require('angular-ui');
    require("uploader");
    require("../../../plugins/select2/select2");
    require('../contract-common');
    var dialog = require('@yunke/art-dialog').default;
    var util = require('@yunke/core/util').default;
    var api_prefix = G_CONFIG["api_prefix"]; //api前缀
    var ui = require("@yunke/core/ui");
    var config = require('../../config');
    var myMath = require('../../common/my-math');
    var authorize = require('../../authorize');

    angular.module('ContractPayinfo', [])
        .filter('sumPayAmount', function () {
            return function (incomes) {
                var amount = 0;
                $.each(incomes, function (i, d) {
                    if (d['__type'] == 'delete') {
                        return;
                    }
                    amount = myMath.add(amount, parseFloat(d.dely_amount));
                });
                return amount;
            }
        })
        .filter('remainPayAmount', function () {
            return function (incomes, paymentAmount) {
                var amount = 0;
                $.each(incomes, function (i, d) {
                    if (d['__type'] == 'delete') {
                        return;
                    }
                    amount = myMath.add(amount, parseFloat(d.dely_amount));
                });
                if (paymentAmount) {
                    // if (contract.contract_property_id == '7f83719a-fce8-11e4-bed8-00155d02c832'
                    //     || contract.contract_property_id == '7f8422d0-fce8-11e4-bed8-00155d02c832') {
                    //云客签约-直属区域/云客签约-联营区域
                    //收入金额汇总 = 签约金额
                    return myMath.sub(paymentAmount, amount);
                    //} else {
                    //    //其他：收入金额汇总=结算金额
                    //    return myMath.sub(contract.balance_amount, amount);
                    //}
                }

                return 0;
            }
        })
        .controller('contractPayinfoCtrl', ['$scope','$filter', '$routeParams', 'contractCommonService', function ($scope,$filter, $routeParams, contractCommonService) {

            var contractId = $routeParams.id;
            //是否区域角色
            authorize.getUserInfoPromise().then((userinfo) => {
                $scope.areaRole = userinfo.areaRole;
            });

            $scope.contractFiles = [];
            $scope.contractPayinfo = [];

            //合同属性
            $scope.attribute_name_text = ['新增','增购','续签'];

            $scope.contractBaseInfo = {customer_property: 0, contract_status: 0};

            if (contractId) {
                //编辑模式先设为只读（复核状态），避免复核的合同先显示编辑按钮再隐藏导致的刷新
                $scope.contractBaseInfo.contract_status = 1;
            }



            $scope.loadContract = function (contractId) {

                if (contractId) {
                    //获取合同信息
                    contractCommonService.getContract(contractId, function (data) {
                        if (data) {
                            $scope.contractBaseInfo = data.contract;
                            $scope.$applyAsync();
                        }
                    })

                    //获取交付信息
                    contractCommonService.getContractSignDelay(contractId, function (data) {
                        $scope.contractPayinfo = data.sign_dely;
                        $scope.contractFiles = data.attachement;
                        $scope.paymentAmount = data.payment_amount;

                        $.map($scope.contractPayinfo,function(n,i){
                            if(n.attribute_name != null){
                                n.attribute_name = n.attribute_name.split(',');
                            }else{ //不存在 ,默认获取合同属性
                                $scope.contractBaseInfo.attribute_name ?
                                    n.attribute_name = $scope.contractBaseInfo.attribute_name.split(",") : n.attribute_name = ["false","false","false"];
                            }

                        });


                        $scope.$applyAsync();
                    });
                }


            }


            //下拉框设置
            //交付归属人
            $scope.ddlConfigBelongBy = {
                allowClear: false,
                ajax: {
                    url: api_prefix + "erp-interface/get-users",
                    dataType: 'json',
                    delay: 250,
                    data: function (term) {
                        return {
                            keyword: term,
                            limit: 10
                        };
                    },
                    results: function (json, page) {
                        var data = [];
                        if (json.retCode === "0") {
                            data = json.data;
                        }
                        return {results: data};
                    },
                    processResults: function (data, page) {
                        // parse the results into the format expected by Select2.
                        // since we are using custom formatting functions we do not need to
                        // alter the remote JSON data
                        return {
                            results: data.items
                        };
                    },
                    cache: true
                },
                escapeMarkup: function (markup) {
                    return markup;
                }, // let our custom formatter work
                minimumInputLength: 1,
                onchange2: function (newVal, scope) {
                    if (scope) {
                        scope.belong_name = newVal.text;
                        scope.area_by = newVal.BUGUID;
                        scope.abu_by = newVal.AubGUID;
                        scope.department_by = newVal.DepartmentId
                        scope.department_name = newVal.DepartmentName;
                        scope.area_name = newVal.BUName;
                    }
                },
                formatResult: formatProposer,
                formatSelection: formatProposerSelection // omitted for brevity, see the source of this page
            };

            function formatProposer(repo) {
                if (repo.loading) return repo.text;

                var markup = '<div class="clearfix" style="width: 300px;">' +
                    '<div class="clearfix">' +
                    '<div class="col-sm-6">' + repo.UserName + '</div>' +
                    '<div class="col-sm-18">' + repo.BUName + '</div>' +
                    '</div></div>';

                return markup;
            }

            function formatProposerSelection(repo) {
                return repo.text;
            }


            //附件上传初始化
            setTimeout(function(){
                $('#fileupload').fileupload({
                    dataType: 'json',
                    url: api_prefix + "/common/file/upload-document",
                    add: function (e, data) {
                        // 大小限制
                        if (data.files.length > 0) {
                            if (data.files[0].size > config.uploader.max_file_size) {
                                util.alert('文件大小超出' + config.uploader.max_file_size_text + '，无法上传。');
                                return;
                            }
                        }
                        data.submit();
                        ui.loading('', '正在上传…');
                    },
                    done: function (e, data) {
                        var res = data.result;
                        if (res.retCode == "0") {
                            var attachement = {
                                __type: 'add',
                                attachement_id: data._time,
                                attachement_name: data.files[0].name,
                                attachement_ext_name: '',
                                attachement_path: res.data.path,
                            };
                            $scope.contractFiles.push(attachement);

                            $scope.$applyAsync();
                            ui.removeLoading();

                            $("#fileupload_error").html("");
                            $("#fileupload_error").hide();
                        } else {
                            ui.removeLoading();
                            $("#fileupload_error").html("上传失败:" + res.errMsg);
                            $("#fileupload_error").show();
                        }
                    },
                    fail: function (e, data) {
                        $("#fileupload_error").html("上传失败:" + data.errorThrown);
                        $("#fileupload_error").show();
                        ui.removeLoading();
                    },
                    always: function (e, data) {
                        ui.removeLoading();
                    }
                });
            },0)


            /**
             * 删除附件
             * @param data
             * @param id
             */
            $scope.delAttachment = function (item, idx) {
                if (item.__type == 'add') {
                    $scope.contractFiles.splice(idx, 1);
                } else {
                    angular.extend(item, {__type: 'delete'});
                }
                $scope.$applyAsync();
            };


            /**
             * 拆分业绩
             * @param items
             */
            $scope.addSignAchievement = function (items, record) {
                var item;
                if (items == $scope.contractPayinfo.paymentAchievement) {
                    item = {
                        receivable_item_id: record.receivable_item_id,
                        receivable_item_name: record.receivable_item_name,
                        money_category_item_id: record.money_category_item_id,
                        money_category_item_name: record.money_category_item_name,
                        editMode: 1,
                        received_time: record.received_time,
                        achievement_belong_time: record.achievement_belong_time,
                        __type: 'add'
                    };
                } else {
                    item = {
                        editMode: 1,
                        achievement_belong_time: record.achievement_belong_time,
                        __type: 'add'
                    };
                }

                items.push(item);
            };

            /**
             * 修改
             * @type {number}
             */
            $scope.editSignAchievement = function (item, idx, items) {
                //先保存原始数据
                item.orginalData = angular.copy(item);
                item.editMode = 2;

                //获取当前修改的人物下拉框
                var n = -2;
                var it;
                for (var i = idx; it = items[i]; i--) {
                    if (it.editMode == 1 || it.editMode == 2) {
                        //每点开一个，会生成2个相同class的元素
                        n += 2;
                    }
                }

                setTimeout(function () {
                    $(".idBelongBy1").eq(n).select2("data", {
                        id: item.achievement_id,
                        text: item.belong_name
                    });
                    $scope.$applyAsync();
                }, 0)

            };

            /**
             * 删除
             * @type {number}
             */
            $scope.delSignAchievement = function (item, idx, items) {
                var it;
                var sum = 0;
                for (var i = 0; it = items[i]; i++) {
                    if (!it.editMode || it.editMode == 0) {
                        sum++;
                    }
                }
                if (sum <= 1) {
                    util.alert('不可删除唯一确定的交付！');
                    return
                }
                util.confirm('确定要删除此交付信息吗？', {
                    ok: function () {
                        if (item.__type == 'add') {
                            items.splice(idx, 1);
                        } else {
                            angular.extend(item, {__type: 'delete', editMode: 3});
                        }
                        $scope.$applyAsync();
                    }
                });
            };

            /**
             * 保存收入信息
             * @type {number}
             */
            $scope.saveSignAchievement = function (item) {
                if (!item.dely_amount) {
                    util.alert('交付业绩金额不能为空');
                    return;
                } else if (!(parseFloat(item.dely_amount) > 0)) {
                    util.alert('交付业绩金额必须为数值且大于0');
                    return;
                } else {
                    var arr = item.dely_amount.split(".");
                    if (arr.length > 2) {
                        util.alert('交付业绩金额只能输入1位小数点');
                        return
                    } else if (arr[1] && arr[1].length > 2) {
                        util.alert('交付业绩金额请保留2位小数');
                        return
                    }
                }

                if (!item.belong_by) {
                    util.alert('交付归属人不能为空');
                    return;
                }

                item.editMode = 0;
                $scope.$applyAsync();
            };

            /**
             * 取消保存
             * @type {number}
             */
            $scope.cancelSignAchievement = function (item, idx, items) {
                if (item.editMode == 1) {
                    items.splice(idx, 1);
                } else {
                    angular.extend(item, item.orginalData);
                    item.editMode = 0;
                }

            };


            /**
             * 保存信息
             */
            $scope.save = function () {
                var url = api_prefix + 'contract/save-sign-dely';



                var restSignAmount = $filter('remainPayAmount')($scope.contractPayinfo,$scope.paymentAmount);



                if (restSignAmount == 0) {

                    $.map($scope.contractPayinfo,function(n,i){
                        n.attribute_name = n.attribute_name.toString();
                    });

                    var data = {
                        contractId: contractId,
                        signDelys: $scope.contractPayinfo,
                        files: $scope.contractFiles
                    };

                    $.ajax({
                        url: url,
                        type: 'POST',
                        dataType: 'json',
                        data: data,
                        success: function (res) {
                            if (res.retCode === "0") {
                                util.alert('保存成功');
                                $scope.loadContract(contractId);
                            } else {
                                util.alert(res.errMsg);
                            }
                        },
                        error: function () {
                            util.alert('系统维护，请稍候重试！');
                        }
                    });
                } else {
                    util.alert('交付业绩金额总和不等于收入金额');
                }
            };

            //页面初始化
            $scope.init = function () {
                $scope.loadContract(contractId);
            };
            $scope.init();
        }])

});
